package com.cheyun.netsalev3.view.dm

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.WindowManager
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.viewpager.widget.ViewPager
import com.cheyun.netsalev3.*
import com.cheyun.netsalev3.adapter.HomePageAdapter
import com.cheyun.netsalev3.databinding.ActivityDmMainBinding
import com.cheyun.netsalev3.utils.BaseActivity
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.viewmodel.DmMainViewModel
import kotlinx.android.synthetic.main.activity_main.*
import androidx.lifecycle.Observer
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.widget.BadgeView
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.utils.ToastUtil

class DmMainActivity : BaseActivity<ActivityDmMainBinding>() {

    override fun initContentView(): Int {
        return R.layout.activity_dm_main
    }

    var showMy = true
    var planType = 1
    var mBadgeViews: HashMap<String, BadgeView>? = HashMap()

    var xktNum = 0
    var zhtNum = 0
    var cztNum = 0
    var chatNum = 0

    var context: Context? = null

    init {

    }

    override fun initViewModel(): ViewModel? {
        val factory = InjectorUtils.getDmMainViewModelFactory()
        return ViewModelProviders.of(this, factory).get(DmMainViewModel::class.java)
    }
    override fun initData() {
        var uid = MySharedPreferences.getDmLoginData()?.user?.user_id?: 0
        setAlias(uid)
//        timLogin()
        checkPermission(this)


    }

    /**
     * 系统请求权限回调
     */
    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        when (requestCode) {
            REQ_PERMISSION_CODE -> if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                ToastUtil.toastLongMessage("未全部授权，部分功能可能无法使用！")
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

//    fun timLogin(){
//        var mobile = MySharedPreferences.getMobile()
//        val userSig = GenerateTestUserSig.genTestUserSig(mobile)
//        TUIKit.login(mobile, userSig, object : IUIKitCallBack {
//            override fun onError(module: String, code: Int, desc: String) {
//                DemoLog.i("tim login", "imLogin errorCode = $code, errorInfo = $desc")
//            }
//
//            override fun onSuccess(data: Any?) {
//                DemoLog.i("tim login", "imLogin success")
//            }
//        })
//    }

    private fun setAlias(uid: Int) {
        if (uid == 0) {
            return
        }
//        JPushInterface.setAlias(this, 1,"DM_USER_"+uid)
    }

    private var listFragmet = ArrayList<Fragment>()

    override fun initView() {
        if(intent.hasExtra("showMy")) {
            showMy = intent.getBooleanExtra("showMy",false);
        }

        listFragmet.add(DmXktFragment())
//        listFragmet.add(DmZhtFragment())
//        listFragmet.add(DmCztFragment())
        listFragmet.add(DmChatFragment())
        listFragmet.add(DmMyFragment())

        binding.dmZht.visibility = View.GONE
        binding.dmCzt.visibility = View.GONE

        val pagerAdapter = HomePageAdapter(supportFragmentManager, listFragmet)
        binding.viewPager.adapter = pagerAdapter
        binding.viewPager.offscreenPageLimit = 4
        binding.dmXkt.isChecked = true
        //设置底部按钮事件
        binding.homeLayout.setOnCheckedChangeListener { group, checkedId ->
            if (showMy) {
                when (checkedId) {
                    R.id.dmXkt -> {
                        viewPager.setCurrentItem(0, true)
                    }
//                    R.id.dmZht -> {
//                        viewPager.setCurrentItem(1, true)
//                    }
//                    R.id.dmCzt -> {
//                        viewPager.setCurrentItem(2, true)
//                    }
                    R.id.dmChat -> {
                        viewPager.setCurrentItem(1, true)
                    }
                    R.id.dmMy -> {
                        viewPager.setCurrentItem(2, true)
                    }
                }
            } else {
                when (checkedId) {
                    R.id.dmXkt -> {
                        viewPager.setCurrentItem(0, true)
                    }
//                    R.id.dmZht -> {
//                        viewPager.setCurrentItem(1, true)
//                    }
//                    R.id.dmCzt -> {
//                        viewPager.setCurrentItem(2, true)
//                    }
                    R.id.dmChat -> {
                        viewPager.setCurrentItem(1, true)
                    }
                }
            }
        }
        //设置滑动监听器
        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                changeBottonView(position)
            }
        })
        remind(binding.btnXktMsg,"xkt")
        remind(binding.btnChatMsg,"chat")
        LiveEventBus.get()
                .with("xktNum", Int::class.java)
                .observe(this, Observer {
                    xktNum = it
                    updateRemind("xkt")
                })
        LiveEventBus.get()
                .with("zhtNum", Int::class.java)
                .observe(this, Observer {
                    zhtNum = it
                    updateRemind("xkt")
                })
        LiveEventBus.get()
                .with("cztNum", Int::class.java)
                .observe(this, Observer {
                    cztNum = it
                    updateRemind("xkt")
                })
        LiveEventBus.get()
                .with("chatNum", Int::class.java)
                .observe(this, Observer {
                    chatNum = it
                    updateRemind("chat")
                })

        LiveEventBus.get()
                .with("changePlanType", Int::class.java)
                .observe(this, Observer {
                    changePlanType(it);
                })
//        binding.dmChat.visibility = View.GONE
//        binding.btnChatMsg.visibility = View.GONE
        context = this
        checkNotificationsEnabled()
        showFloatView()
    }

    private fun changePlanType(t:Int){
        if(t == planType) return
        this.planType = t
        if(planType == 1){
            binding.dmZht.visibility = View.GONE
            binding.dmCzt.visibility = View.GONE
            binding.dmXkt.visibility = View.VISIBLE
            changeBottonView(0);
        }else if(planType == 2){
            binding.dmXkt.visibility = View.GONE
            binding.dmCzt.visibility = View.GONE
            binding.dmZht.visibility = View.VISIBLE

            changeBottonView(1);
        }else if(planType == 3){
            binding.dmZht.visibility = View.GONE
            binding.dmXkt.visibility = View.GONE
            binding.dmCzt.visibility = View.VISIBLE

            changeBottonView(2);
        }
        updateRemind("xkt")
    }

    private fun changeBottonView(position: Int) {
        if (showMy) {
            when (position) {
                0 -> homeLayout.check(R.id.dmXkt)
//                1 -> homeLayout.check(R.id.dmZht)
//                2 -> homeLayout.check(R.id.dmCzt)
                1 -> homeLayout.check(R.id.dmChat)
                2 -> homeLayout.check(R.id.dmMy)
            }
        } else {
            when (position) {
                0 -> homeLayout.check(R.id.dmXkt)
//                1 -> homeLayout.check(R.id.dmZht)
//                2 -> homeLayout.check(R.id.dmCzt)
                1 -> homeLayout.check(R.id.dmChat)
            }
        }
    }

    private fun remind(view: View,key:String) { //BadgeView的具体使用
        // 创建一个BadgeView对象，view为你需要显示提醒的控件
        val badge1 = BadgeView(this, view)
        // 需要显示的提醒类容

        // 显示的位置.右上角,BadgeView.POSITION_BOTTOM_LEFT,下左，还有其他几个属性
        badge1.badgePosition = BadgeView.POSITION_CENTER_TOP
        // 文本颜色
        badge1.setTextColor(Color.WHITE)
        // 提醒信息的背景颜色，自己设置
        badge1.badgeBackgroundColor = Color.RED
        //还可以设置背景图片
        //badge1.setBackgroundResource(R.mipmap.icon_message_png);
        // 文本大小
        badge1.textSize = 11f
        // 水平和竖直方向的间距
//        badge1.setBadgeMargin(3, 3);
        //各边间隔
        badge1.setBadgeMargin(5)
        //显示效果，如果已经显示，则隐藏，如果隐藏，则显示
        // badge1.toggle();
        badge1.hide()
        mBadgeViews?.put(key,badge1);

    }

    private fun updateRemind(key:String) {
        var badge = mBadgeViews?.get(key)
        var num = 0;
        if(key.equals("chat")){
            num = chatNum
        }else{
            if(planType == 1){
                num = xktNum
            }
            if(planType == 2){
                num = zhtNum
            }
            if(planType == 3){
                num = cztNum
            }
        }
        badge?.text = if(num>99) "99+" else num.toString()
        if(num>0)
            badge?.show()
        else
            badge?.hide()
    }

    private val REQ_PERMISSION_CODE = 0x100
    //权限检查
    fun checkPermission(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val permissions = java.util.ArrayList<String>()
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            if (permissions.size != 0) {
                val permissionsArray = permissions.toTypedArray()
                ActivityCompat.requestPermissions(activity,
                        permissionsArray,
                        REQ_PERMISSION_CODE)
                return false
            }
        }

        return true
    }

    //悬浮窗权限开启
    private fun showFloatView(){
        //开启悬浮窗
//        val isPermission = FloatPermissionManager.getInstance().applyFloatWindow(this)
        //有对应权限或者系统版本小于7.0
//        if (isPermission || Build.VERSION.SDK_INT < 24) {
//            FloatActionController.getInstance().startMonkServer(this)
//        }
//        handler.postDelayed(runnable, 1500);
    }

    private fun checkNotificationsEnabled(){
        if (!NotificationManagerCompat.from(MyApplication.getInstance().baseContext).areNotificationsEnabled()) {
            DialogUIUtils.showAlert(this, "通知打开提醒", "为保证及时收到推送消息，请您手动将通知开启", object : DialogUIListener() {
                override fun onPositive() {
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT <  Build.VERSION_CODES.O) {
                        var intent = Intent()
                        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS")
                        intent.putExtra("app_package", MyApplication.getInstance().packageName)
                        intent.putExtra("app_uid", context?.getApplicationInfo()?.uid)
                        startActivity(intent);
                    } else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                        var intent = Intent()
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + MyApplication.getInstance().packageName));
                        startActivity(intent);
                    } else {
                        var localIntent = Intent()
                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        localIntent.setData(Uri.fromParts("package", MyApplication.getInstance().packageName, null));
                        startActivity(localIntent);
                    }
                }

                override fun onNegative() {
                    DemoLog.d("aa","bbbbbbbbb")
                }

            }).show()
        }else{
            var win = getWindow()
            win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
        }
    }

    override fun onResume() {
        super.onResume()
        showFloatView()
//        checkNotificationsEnabled()
    }

}
